package org.lboot.idmo.custom.device;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.lboot.core.auth.anno.AuthLogin;
import org.lboot.core.domain.ResponseDTO;
import org.lboot.idmo.custom.device.params.FdDeviceCreateParams;
import org.lboot.idmo.module.user.SysUser;
import org.lboot.idmo.module.user.SysUserService;
import org.springframework.http.HttpStatus;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

@Slf4j
@RestController
@RequestMapping("fd")
@AllArgsConstructor
@Api(tags = "设备管理")
public class FdDeviceController {
    FdDeviceService fdDeviceService;

    SysUserService userService;

    @PostMapping("devices")
    @ApiOperation(value = "设备绑定新增")
    public ResponseDTO<Object> bindDevice(@Validated @RequestBody FdDeviceCreateParams params){
        Long userId = params.getUserId();
        Optional<SysUser> userOp = userService.getOne(userId);
        if (!userOp.isPresent()){
            return ResponseDTO.wrap(HttpStatus.NOT_FOUND,"没有对应用户信息");
        }
        FdDevice device = new FdDevice();
        BeanUtil.copyProperties(params, device, CopyOptions.create().setIgnoreError(true).setIgnoreNullValue(true));
        return ResponseDTO.succData(
                fdDeviceService.saveOne(device)
        );
    }

    @DeleteMapping("devices/{id}")
    @ApiOperation(value = "删除设备绑定关系")
    public ResponseDTO<Object> deleteDevice(@PathVariable("id") Long id){
        fdDeviceService.deleteOne(id);
        return ResponseDTO.succ();
    }


    @AuthLogin
    @GetMapping("devices")
    @ApiOperation(value = "获取设备列表")
    public ResponseDTO<Object> queryDevice(){
        Long loginId = StpUtil.getLoginIdAsLong();
        List<FdDevice> devices = fdDeviceService.getByUserId(loginId);
        return ResponseDTO.succData(devices);
    }


}
